<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单项调节各地区占比</title>
    <script src="./js/chart.js"></script>
    <script src="./js/xlsx.full.min.js"></script>
    <script src="./js/echarts.min.js"></script>
    <script src="./js/echarts_china.js"></script>
    <!-- <script src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/dataTool"></script> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script> -->
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        #chartContainer {
            width: 80%;
            margin: 0 auto;
        }
        #mapContainer {
            width: 80%;
            /* height: 80%; */
            height: 400px;
            margin: 20px auto;
        }
        select {
            margin-bottom: 20px;
        }
        table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
            text-align: center;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
        nav {
            margin-bottom: 20px;
        }
        nav a {
            margin: 0 10px;
            text-decoration: none;
            color: #007BFF;
            font-weight: bold;
        }
        nav a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <nav>
        <a href="index.html">调节服务占比可视化</a>
        <a href="single_service.html">单项调节各地区占比</a>
        <a href="calculate_service_percentage.html">计算调节服务占比</a>
        <a href="adjust_service_value.html">调整气候调节服务项的价值量</a>
    </nav>
    <h1>单项调节各地区占比</h1>
    <input type="file" id="fileInput" accept=".xlsx, .xls">
    <select id="serviceSelect">
        <option value="">请选择调节服务项</option>
    </select>
    <div id="chartContainer">
        <canvas id="singleServiceChart"></canvas>
    </div>
    <div id="mapContainer"></div>
    <table id="dataTable">
        <thead>
            <tr>
                <th>行政区划代码</th>
                <th>核算地区</th>
                <th>面积（km²）</th>
                <th>调节服务项</th>
                <th>生态系统</th>
                <th>实物量总值（t）</th>
                <th>价格（元/t）</th>
                <th>价值量总值（元）</th>
                <th>调节服务项占比（%）</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script>
        let chartInstance = null; // 用于存储当前的图表实例
        let myChart = null;

        document.getElementById('fileInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const data = e.target.result;
                    const workbook = XLSX.read(data, {type: 'binary'});
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});

                    // Extract headers
                    const headers = jsonData[0];
                    const regionIndex = headers.indexOf('核算地区');
                    const serviceIndex = headers.indexOf('调节服务项');
                    const percentageIndex = headers.indexOf('调节服务项占比（%）');

                    // Extract unique services
                    const services = Array.from(new Set(jsonData.slice(1).map(row => row[serviceIndex])));

                    // Populate the service select box
                    const serviceSelect = document.getElementById('serviceSelect');
                    serviceSelect.innerHTML = '<option value="">请选择调节服务项</option>';
                    services.forEach(service => {
                        const option = document.createElement('option');
                        option.value = service;
                        option.textContent = service;
                        serviceSelect.appendChild(option);
                    });

                    // Function to draw the bar chart and update the table
                    function drawChart(selectedService) {
                        // Filter data for the selected service
                        const filteredData = jsonData.slice(1).filter(row => row[serviceIndex] === selectedService);

                        // Extract regions and their corresponding percentages
                        const regions = filteredData.map(row => row[regionIndex]);
                        const percentages = filteredData.map(row => parseFloat(row[percentageIndex]));

                        // Destroy the previous chart instance if it exists
                        if (chartInstance) {
                            chartInstance.destroy();
                        }

                        // Draw the bar chart
                        const ctx = document.getElementById('singleServiceChart').getContext('2d');
                        chartInstance = new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: regions,
                                datasets: [{
                                    label: `${selectedService}占比`,
                                    data: percentages,
                                    backgroundColor: [
                                        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    title: {
                                        display: true,
                                        text: `单项调节各地区占比 - ${selectedService}`
                                    }
                                },
                                scales: {
                                    y: {
                                        beginAtZero: true,
                                        title: {
                                            display: true,
                                            text: '占比 (%)'
                                        }
                                    }
                                }
                            }
                        });

                        // Update the table
                        updateTable(filteredData);

                        // Draw the map
                        // 首先，我们需要将原始数据转换为 ECharts 地图组件需要的格式
                        // 处理地区名称的函数
                        function formatRegionName(name) {
                            // 特殊处理的地区名称
                            const specialCases = {
                                '广西壮族自治区': '广西',
                                '内蒙古自治区': '内蒙古',
                                '宁夏回族自治区': '宁夏',
                                '新疆维吾尔自治区': '新疆',
                                '西藏自治区': '西藏',
                                '特别行政区': '', // 假设没有特别行政区的数据，如果有需要添加
                            };

                            // 检查是否有特殊处理的情况
                            if (specialCases[name]) {
                                return specialCases[name];
                            }

                            // 去掉地区名称中的后缀
                            const suffixesToRemove = ['省', '市'];
                            for (let suffix of suffixesToRemove) {
                                if (name.endsWith(suffix)) {
                                    return name.slice(0, -suffix.length);
                                }
                            }
                            return name;
                        }
                        const transMapData = filteredData.map(item => {
                            // item 是一个数组，我们直接通过索引访问数据
                            // 地区名称是数组的第二个元素（索引为1）
                            // 调节服务项占比是数组的倒数第一个元素（索引为item.length - 1）
                            return {
                                name: formatRegionName(item[1]), // 地区名称在数组的第二个位置 
                                value: parseFloat(item[item.length - 1]).toFixed(2), // 调节服务项占比，转换为浮点数
                            };
                        });


                        // const transMapData = [
                        // {name: '北京',value: randomData() },
                        // {name: '天津',value: randomData() },
                        // {name: '上海',value: randomData() },
                        // {name: '重庆',value: randomData() },
                        // {name: '河北',value: randomData() },
                        // ]
                        drawMap(transMapData);
                        console.log('Map data输入', transMapData);
                    }

                    // Function to update the table
                    function updateTable(data) {
                        const tableBody = document.getElementById('dataTable').getElementsByTagName('tbody')[0];
                        tableBody.innerHTML = '';

                        data.forEach(row => {
                            const tr = document.createElement('tr');
                            headers.forEach((header, index) => {
                                const td = document.createElement('td');
                                td.textContent = row[index];
                                tr.appendChild(td);
                            });
                            tableBody.appendChild(tr);
                        });
                    }

                    // Function to draw the map
                    function drawMap(data) {
                        const mapContainer = document.getElementById('mapContainer');
                        if (myChart) {
                            myChart.dispose();
                        }
                        myChart = echarts.init(mapContainer);
                        // const mapData = data.map(item => ({
                        //     name: item[regionIndex],
                        //     value: parseFloat(item[percentageIndex])
                        //     // name: item[1], // 地区名称
                        //     // value: parseFloat(item[item.length - 1]) // 调节服务项占比，转换为浮点数
                        // }));
                        const mapData = data;

                        console.log('Map data地图接受到的', mapData);

                        const option = {
                            title: {
                                text: '气候调节各省的占比地图',
                                subtext: '未确认数据',
                                left: 'center'
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: '{b}<br/>占比: {c}%'
                            },
                            legend: {
                                orient: 'vertical',
                                left: 'left',
                                data:['调节服务项占比']
                            },
                            visualMap: {
                                min: 0,
                                max: 100,
                                left: 'left',
                                top: 'bottom',
                                text: ['高', '低'], // 文本，默认为数值文本
                                calculable: true,
                                // inRange: {
                                //     color: ['#e0ffff', '#006edd']
                                // }
                            },
                            series: [
                                {
                                    name: '调节服务项占比',
                                    type: 'map',
                                    mapType: 'china',
                                    roam: false,
                                    label: {
                                        show: true
                                    },
                                    emphasis: {
                                        show: true
                                    },
                                    data: mapData
                                }
                            ]
                        };

                        myChart.setOption(option);
                    }

                    // Event listener for service selection
                    serviceSelect.addEventListener('change', function() {
                        const selectedService = serviceSelect.value;
                        if (selectedService) {
                            drawChart(selectedService);
                        } else {
                            // Clear the canvas and table if no service is selected
                            const ctx = document.getElementById('singleServiceChart').getContext('2d');
                            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                            document.getElementById('dataTable').getElementsByTagName('tbody')[0].innerHTML = '';
                            if (myChart) {
                                myChart.dispose();
                            }
                        }
                    });
                };
                reader.readAsBinaryString(file);
            }
        });
    </script>
</body>
</html>